<?php

namespace App\Http\Middleware;

use App\Repository\Commit\DeptRepository;
use App\Repository\MenuRepository;
use App\Repository\RoleRepository;
use Closure;


class AdminRoleMiddleware
{
    private $model;
    private $menu;
    private $dept;
    private $prefix;

    public function __construct(RoleRepository $RoleRepository, MenuRepository $MenuRepository, DeptRepository $DeptRepository)
    {
        $this->model = $RoleRepository;
        $this->menu = $MenuRepository;
        $this->dept = $DeptRepository;
        $this->prefix = 'dev-api'; // 请求路径的前缀
    }

    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // if (!$request->hasHeader('Authorization')) {
        //   return response(array(
        //     'code'      =>  '10005',
        //     'info'      =>  '缺少用户信息',
        //     'data'      =>  null,
        //   ));
        // };
//        if ($request->has('dateRange') && !empty($request->get('dateRange'))) {
//            $dateRange = $request->get('dateRange');
//            $dateRange = [date('Y-m-d H:i:s', strtotime($dateRange[0])), date('Y-m-d', strtotime($dateRange[1])) . ' 23:59:59'];
//            $request->merge(['dateRange' => $dateRange]);
//        }
        // $token =   $request->header('Authorization');
        try {
            //判断用户的权限信息
            $dept_id = !empty($request->user->dept_id) ? $request->user->dept_id : '';
            $role_id = !empty($request->user->role_id) ? $request->user->role_id : '';
            if (!empty($dept_id)) {
                $DeptArr = $this->dept->getOne(['dept_id' => $dept_id]);
//                print_r($DeptArr);
                if (!empty($DeptArr)) {
                    $role_id = $DeptArr->role_id;
                    // return response(array(
                    //   'code'      =>  '10007',
                    //   'msg'      =>  '您无法登录后台',
                    //   'data'      =>  [],
                    // ));
                }
            }
            if (empty($role_id)) {
                return response(array(
                    'code' => '10007',
                    'msg' => '您无法登录后台',
                    'data' => [],
                ));
            }

            $where = [
                'role_id' => explode(',', $role_id),

            ];
            $res = $this->model->getPerm($where);
            if (empty($res)) {
                return response(array(
                    'code' => '10007',
                    'msg' => '您没有该权限',
                    'data' => [],
                ));
            }
            if (empty($res) && (empty($res['in_ids']) && empty($res['ex_ids']))) {
                return response(array(
                    'code' => '10008',
                    'msg' => '您无法登录',
                    'data' => [],
                ));
            }

            if (!empty($res['in_ids'][0]) && $res['in_ids'][0] == '*') {
                return $next($request);
            }
//            dump($request);
//            $path = basename($request->path()); // api/v1/user  // api/v1/user/1
//            // api/v1/user  // api/v1/user/1
            $path = ltrim($request->getPathInfo(), '/');
//            echo $path;
            // $path = str_replace('Hk_', '', $path);
            // $path = str_replace('HK_', '', $path);
            $isOrder = strpos($path, 'Hk_');
            $isOrderTwo = strpos($path, 'HK_');
            $isOrderT = strpos($path, 'Y');

            if (is_numeric($path) || $isOrder === 0 || $isOrderTwo === 0 || $isOrderT === 0) {
                $path = dirname($request->path());
            }
//            原来的用get与delete的方式用的CURD方式的参数处理
            $id = basename($path);
            if ($request['id'] == $id) {
                $path = str_replace('/' . $id, '', $path);
            }
            $wherePath = [
                'back_query' => preg_replace("/[\/]?" . $this->prefix . '\//', '', $path), //
                'back_path' => strtolower($request->method()), // get put post delete
            ];

//            print_r($wherePath);
//            echo $path;
//            不用检测角色权限,但要求登陆的方法
            if ($this->freeRolePerm($path)) {
                if ($request['user']['id'] <= 0) {
                    return response(array(
                        'code' => ERROR_NONE_LOGIN_CODE,
                        'msg' => '请登陆后操作',
                        'data' => [],
                    ));
                }
                return $next($request);
            }
            $isDiled = in_array($path, $this->getFilterPerm());
            if ($isDiled) {
                return $next($request);
            }
            // var_dump(dirname($request->path()), 3333333);
            $isMoreDiled = in_array(str_replace($this->prefix . '/', '', dirname($request->path())), $this->getFilterPermMore());
            if ($isMoreDiled) {
                return $next($request);
            }
//            var_dump($wherePath, 111111111111);
            $menuArr = $this->menu->getOne($wherePath);
//            print_r($menuArr);
            if (empty($menuArr)) {
                return response(array(
                    'code' => -200,
                    'msg' => '请联系管理员添加该权限'
                ));
            }
            $menuId = $menuArr->menu_id;
            if (!empty($res['in_ids'])) {
                if (!in_array($menuId, $res['in_ids'])) {
                    return response(array(
                        'code' => '10009',
                        'msg' => '请联系老板给您开启权限:' . $menuId,
                        'data' => [],
                    ));
                }
            }
            if (empty($res['in_ids']) && !empty($res['ex_ids'])) {
                if (!in_array($menuId, $res['ex_ids'])) {
                    return response(array(
                        'code' => '10010',
                        'msg' => '请老板给您开启权限:' . $menuId,
                        'data' => [],
                    ));
                }
            }
        } catch (\Exception $e) {

            return response(array(
                'code' => 10005,
                'msg' => '请联系管理员' . $e->getMessage(),
                'data' => [],
            ));
        }

        return $next($request);
    }

    //过滤权限
    public function getFilterPerm()
    {
        return [
            $this->prefix . '/dictSingleTypeValue',
//            只更新自己的在线状态
            $this->prefix . '/updateOnline',
//            首页图表数据
            $this->prefix . '/dashboard',
//            统计图表数据
            $this->prefix . '/chatReport',
//            修改自己头像
            $this->prefix . '/userProfileAvatar',
            $this->prefix . '/getRouters',
            $this->prefix . '/getInfo',
            $this->prefix . '/userProfile',
            $this->prefix . '/getAppH5Config',
            $this->prefix . '/uploadPdf',
            $this->prefix . '/uploadMp3',
            $this->prefix . '/uploadPic',
        ];
    }

//    有时候拉一些选择项的内容,也不用权限设置那么麻烦,直接放开
//      ApiBackSave是一些前端调用抓取数据后要保存的接口
//      OptionsList是一些给前端展示的选项内容
    public function freeRolePerm($urlPath)
    {
        $endStringArray = ['OptionsList', 'ApiReturn'];
        $result = false;
        for ($i = 0; $i < count($endStringArray); $i++) {
            $endString = $endStringArray[$i];
            $len = strlen($endString);
            $result = (substr($urlPath, -$len) === $endString);
            if ($result) {
                break;
            }
        }
        return $result;
    }

    public function getFilterPermMore()
    {
        return [
            'dictData',
            'configData'
        ];
    }
}
